<template>
	<section>
		<!--工具条 +关键字查询+新增-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="关键字查询"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery" v-perm="'department:list'" icon="el-icon-zoom-in">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" v-perm="'department:save'" icon="el-icon-circle-plus">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表数据-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" :row-key="getKey" ref="multiTable"  style="width: 100%;">
			<el-table-column type="selection" width="55" :reserve-selection="true">
			</el-table-column>
			<el-table-column type="index" label="序号"width="60">
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable>
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="100"  sortable>
			</el-table-column>
			<el-table-column prop="dirPath" label="部门层级" width="160" >
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="120" sortable>
        <template scope="scope" >
          <span v-if="scope.row.state==0"  style="color: red">禁用</span>
          <span v-if="scope.row.state==1"  style="color: springgreen">启用</span>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="180" >
			</el-table-column>
			<el-table-column prop="parentId" label="上级部门" width="180" >
        <template scope="scope" >
          <span v-if="scope.row.parent==null"  style="color: #0082e6">顶级部门</span>
          <span v-else  style="color: magenta">{{scope.row.parent.name}}</span>
        </template>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button type="warning" size="small" @click="handleEdit(scope.$index, scope.row)" icon="el-icon-edit-outline">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" v-perm="'department:delete'"   icon="el-icon-delete" >删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条+批量删除+分页栏-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'department:patchDel'"   icon="el-icon-finished">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage"
                     style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增+编辑界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false"
               :destroy-on-close="true">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="saveForm.sn" placeholder="请输入部门编号" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name"  placeholder="请输入部门名称" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="分类层级" prop="dirPath">
					<el-input v-model="saveForm.dirPath" placeholder="请输入分类层级"  auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门状态" prop="state">
          <el-radio-group v-model="saveForm.state">
            <el-radio :label="1"border >启用</el-radio>
            <el-radio :label="0"border >禁用</el-radio>
          </el-radio-group>
				</el-form-item>
				<el-form-item label="管理员" prop="managerId">
          <el-select v-model="saveForm.managerId" clearable  placeholder="请选择管理员">
            <el-option v-for ="item in managers"
                       :label="item.username"
                       :value="item.id"
                       clearable>
              <span style="float: left">{{ item.username }} </span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>

         <!--
                el-cascader - 级联框
                v-model="saveForm.parent_id" - 双向绑定

                  label: 'name', - 回显哪一个属性值
                    value: 'id' - 传值哪一个属性值
                回显机制【修改】：
                  1.定位：v-model="saveForm.parent_id" 与 deptTree中的每一个对象的id 定位
                  2.显示哪一个属性值：label: 'name',  回显对象的name属性值
                传值机制：
                  ？？
        -->
        <el-form-item label="上级部门" prop="parentId" v-if="!saveForm.id || this.saveForm.parentId">
          <el-cascader v-model="saveForm.parentId" placeholder="请选择上级部门"
                       :options="deptTree"
                       :props="{checkStrictly: true,
                                        label: 'name',//回显的字段
                                        value: 'id'}"
                       clearable>
          </el-cascader>
        </el-form-item>


			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false" icon="el-icon-close">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading" icon="el-icon-check">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	export default {
		data() {
			return {
			  //1.分页列表展示的相关数据
        departments: [],   //列表数据
        listLoading: false,//关闭加载框
        pageSize:5,        //当前页数
        currentPage:1,     //当前页
        totals:0,          //总条数

        //2.关键字查询
        keyword:'',

        //3.新增/修改
        saveFormVisible: false,//新增/编辑界面是否显示
        title:'',             //新增/修改各自变换标题
        saveForm: {           //新增/修改模型数据
          id: null,
          sn: '',
          name: '',
          dirPath: '',
          state: '',
          managerId: null,
          parentId: null,
        },
        saveLoading: false,     //保存的加载框 - 默认不显示

        //4.批量删除
        sels: [],//列表选中列

        //5.查询部门管理员--员工
        managers:{},

        //6.查询上级部门--部门树
        deptTree:{},

        //7.校验表单项里面的数据u
        saveFormRules: {
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' },
            { required: true, message: '请输入部门编号', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入部门名称', trigger: 'blur' },
            { required: true, message: '请输入部门名称', trigger: 'change' }
          ],
          dirPath: [
            { required: true, message: '请输入部门路径', trigger: 'blur' },
            { required: true, message: '请输入部门路径', trigger: 'change' }
          ],

        },
			}
		},
		methods: {

      //1.获取用户列表---分页
      getDepartments() {
        let para = {
          pageSize: this.pageSize,        //当前的页数
          currentPage: this.currentPage,  //当前页
          keyword: this.keyword,          //关键字查询
        };
        this.listLoading = true ;         //打开加载框
        this.$http.post("/department",para).then(res=>{
          this.departments=res.data.data; //给模型数据赋值
          this.totals=res.data.totals;    //计算总条数
          this.listLoading = false;       //关闭加载框
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后再试【400,404】")
        })

      },

      //2.点击分页实现
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getDepartments();
      },

      //3.高级查询
      keywordQuery(){
        this.currentPage = 1;
        this.getDepartments();
      },

      //4.显示新增界面
      handleAdd: function () {
        this.saveFormVisible = true;
        this.title="新增",
        //重置from表单
        this.saveForm = {
          id: null,
          sn: '',
          name: '',
          dirPath: '',
          state: 1,
          managerId: null,
          parentId: null,
        };
        //查询部门管理员
        this.getEmployees();
        //查询上级部门
        this.getDeptTree();
      },

      //5.显示修改界面
      handleEdit: function (index, row) {
        this.title="修改";
        //弹出对话框
        this.saveFormVisible = true;
        //回显数据：创建一个新的空对象{}，然后将row中的数据拷贝一份给{}
        this.saveForm = Object.assign({}, row);
        //查询部门管理员
        this.getEmployees();
        //查询上级部门
        this.getDeptTree();
      },

      //6..删除功能逻辑
      handleDel: function (index, row) {
        //elementUi提供确认框 - 点确定之后执行then里面的代码，点击取消执行catch中的逻辑
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true; //显示加载框
          this.$http.delete("/department/"+row.id).then(res=>{
            this.listLoading = false; //关闭加载框
            if(res.data.success){
              this.$message.success("删除成功"); //提示成功消息

              //删除成功之后对当前页的处理【特殊情况：删除最后一页的最后一条数据】
              var totalPage = Math.ceil(this.totals/this.pageSize); //总页数 = 最后一页
              //如果当前页是最后一页                  并且是最后一条数据                  并且不是第一页
              if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
                this.currentPage--;
              }
              this.getDepartments();
            }else{
              this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
            }
          }).catch(res=>{
            this.$message.error("系统繁忙，请稍后重试!!![400,404]");
          })
        }).catch(() => {
          this.$message.info("已取消操作");
          this.$refs.multiTable.clearSelection();
        });
      },

      //7.批量删除
      selsChange: function (sels) {
        this.sels = sels;
      },

      //7.跨页批量删除
      getKey(row){
        return row.id;},

      //7.批量删除逻辑
      batchRemove: function () {
        //获取数组中每一个对象的id 并形成新的数组
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认批量删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true; //显示加载框
          this.$http.patch("/department",ids).then(res=>{
            this.listLoading = false; //隐藏加载框
            if(res.data.success){ //操作成功
              this.$message.success("批量删除成功"); //提示成功消息
              //清空批量删除的事件
              this.$refs.multiTable.clearSelection();
              //批量删除后---当前页值为1
              this.currentPage=1;
              this.getDepartments();
            }else{ //操作失败
              this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
            }
          }).catch(res=>{
            this.$message.error("系统繁忙，请稍后重试!!![400,404]");
          })
        }).catch(() => {
          this.$message.info("已取消操作");

        });
      },

      //8.提交新增表单数据   点击保存提交数据到后端
      saveSubmit: function () {
        //表单验证：表单项中任何一个验证不通过，都不能点击提交
        //所有的ref中名称为saveForm的表单
        this.$refs.saveForm.validate((valid) => {
          if (valid) { //表单验证通过 => 每一个表单项都通过了
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true; //显示加载框
              //从表单里回显参数
              //let para = Object.assign({}, this.saveForm);
              //对无限级树 上级部门 的处理 - 没有无限级树不需要处理
              //1.不修改上级部门，没有点级联框：2
              //2.不修改上级部门，点了级联框选择过其他部门：[ 2 ]
              //3.去掉上级部门：[]
              //4. [ 3, 9, 12 ]
              //5. null
              // var isArr = para.parentId;
              // if(Array.isArray(isArr)){
              //   if(isArr.length==0){//空数组
              //     para.parentId = null;
              //   }else{
              //     para.parentId = isArr[isArr.length - 1];
              //   }
              // }
              //无限极树的数据处理
              let temp = this.saveForm.parentId;//null,2,[ 1 ],[ 2，5,6 ][]
              if(temp==null || temp.length==0){
                this.saveForm.parentId = null;
                }else if(temp.length){
                this.saveForm.parentId = temp[temp.length-1];
              }
              this.$http.put("/department",this.saveForm).then(res=>{
                this.saveLoading = false;  //关闭加载框
                this.saveFormVisible = false; //关闭对话框
                if(res.data.success){
                  this.$message.success(this.title+" : 操作成功"); //提示成功消息
                  this.getDepartments();    //重新加载新列表的数据
                }else{
                  //this.$message.error("系统繁忙，请稍后重试!!![500]");
                  //打印后端的错误信息
                  this.$message.error(res.data.message);
                }
              }).catch(res=>{
                this.saveLoading = false;  //关闭加载框
                this.saveFormVisible = false; //关闭对话框
                this.$refs.saveForm.clearValidate();//清除提示
                this.$message.error("系统繁忙，请稍后重试!!![400,404]");
              })
            });
          }
        });
      },

      //9.查询部门管理员
      getEmployees() {
        this.$http.get("/employee").then(res => {
          if (res) {
            this.managers = res.data; //查询部门管理员
          }
        })
      },

      //10.查询上级部门
      getDeptTree() {
        this.$http.get("/department/deptTree").then(res => {
          if (res) {
            this.deptTree = res.data;         //查询上级部门
          }
        })
      },

		},
		mounted() {
		  //页面加载就调用这个方法
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>